package models
type UserExamQuestion struct {
	Id           int `json:"id" xorm:"not null pk autoincr comment('主键') INT(11)"`
	ExamId int `json:"exam_id" xorm:"not null comment('试卷ID主键')  INT(11)"`
	QuestionId int `json:"question_id" xorm:"not null comment('题目主键') INT(11)"`

}
var userexamquestion ="user_exam_question"

func(q *UserExamQuestion) GetRow() bool {
	has, err := mEngine.Get(q)
	if err==nil &&  has  {
		return true
	}
	return false
}

func(q *UserExamQuestion) RemoveQuestionFromExam() error{
		session := mEngine.NewSession()
		defer session.Close()
		// add Begin() before any action
		if err := session.Begin(); err != nil {
			// if returned then will rodefer session.Close()llback automatically
			return err
		}
		if _, err := mEngine.Exec("delete from "+userexamquestion+" where exam_id =? and question_id =? ",q.ExamId,q.QuestionId); err != nil {
			return err
		}

		//删除孤立的试卷
		if _, err :=mEngine.Exec("delete from "+userexam+" where not exists (select 1 from "+userexamquestion+" where "+userexamquestion+".exam_id ="+userexam+".id )"); err != nil {
			return err

		}
		return session.Commit()



}
func(q *UserExamQuestion) GetByExamId(examId int) ([]int,error) {


	var questionIds []int

	err := mEngine.Table(userexamquestion).Cols("question_id").Where(" exam_id=? " , examId).
	Find(&questionIds)

	if err!=nil  {
		return questionIds,err
	}
	return questionIds,err
}

